import { invoke } from '@tauri-apps/api/core';
import { User, LoginCredentials, RegisterData } from '@/types/auth';
import { TauriApiResponse } from '@/types/api';

export const authService = {
  async login(credentials: LoginCredentials): Promise<TauriApiResponse<User>> {
    try {
      return await invoke('auth_login', { credentials });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Login failed',
      };
    }
  },

  async register(data: RegisterData): Promise<TauriApiResponse<User>> {
    try {
      return await invoke('auth_register', { data });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Registration failed',
      };
    }
  },

  async logout(): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('auth_logout');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Logout failed',
      };
    }
  },

  async getCurrentUser(): Promise<TauriApiResponse<User>> {
    try {
      return await invoke('auth_get_current_user');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to get current user',
      };
    }
  },

  async updateProfile(data: Partial<User>): Promise<TauriApiResponse<User>> {
    try {
      return await invoke('auth_update_profile', { data });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Profile update failed',
      };
    }
  },

  async changePassword(oldPassword: string, newPassword: string): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('auth_change_password', { oldPassword, newPassword });
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Password change failed',
      };
    }
  },

  async deleteAccount(): Promise<TauriApiResponse<void>> {
    try {
      return await invoke('auth_delete_account');
    } catch (error) {
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Account deletion failed',
      };
    }
  },

  // Token management (stored in localStorage)
  getToken(): string | null {
    return localStorage.getItem('auth_token');
  },

  setToken(token: string): void {
    localStorage.setItem('auth_token', token);
  },

  removeToken(): void {
    localStorage.removeItem('auth_token');
  },

  isAuthenticated(): boolean {
    const token = this.getToken();
    return token !== null && token.length > 0;
  },
};
